package com.feonix.common.validation;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import com.feonix.common.util.SpringUtil;
import com.feonix.common.util.StringUtil;

import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;

public class ValidationUtil {

	/**
	 * 验证,当不符合将抛出注释的提示信息
	 * 
	 * @param object
	 *            需要验证的bean
	 * @throws ValidationException
	 */
	public static void validation(Object object) throws ValidationException {
		Validator validator = new Validator();
		List<ConstraintViolation> constraintViolationList = validator.validate(object);
		if (CollectionUtils.isNotEmpty(constraintViolationList)) {
			String message = constraintViolationList.get(0).getMessage();
			if (StringUtil.isNotEmpty(message)) {
				message = SpringUtil.getMessage(message);
			}
			throw new ValidationException(message);
		}
	}

	/**
	 * 获得验证的信息，如果验证通过则返回null
	 * 
	 * @param object
	 *            需要验证的bean
	 * @return
	 */
	public static List<String> getValidationMessage(Object object) {
		Validator validator = new Validator();
		List<ConstraintViolation> violationList = validator.validate(object);
		ArrayList<String> messageList = null;
		if (CollectionUtils.isNotEmpty(violationList)) {
			messageList = new ArrayList<String>();
			String message = null;
			for (ConstraintViolation constraintViolation : violationList) {
				message = constraintViolation.getMessage();
				if (StringUtil.isNotEmpty(message)) {
					message = SpringUtil.getMessage(message);
				}
				messageList.add(message);
			}
		}
		return messageList;
	}
}
